<?php

class Reale_Model_Users_AgentMapper
{
	/**
     * @var Zend_Db_Table_Abstract
     */
    protected $_dbTable;

    /**
     * Specify Zend_Db_Table instance to use for data operations
     * 
     * @param  Zend_Db_Table_Abstract $dbTable 
     * @return Reale_Model_Users_AgentMapper
     */
    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    /**
     * Get registered Zend_Db_Table instance
     *
     * Lazy loads Reale_Model_DbTable_Agent if no instance registered
     * 
     * @return Zend_Db_Table_Abstract
     */
    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Reale_Model_DbTable_Agent');
        }
        return $this->_dbTable;
    }
    
    /**
     * 
     * Checks username for availability.
     * 
     *  @return Boolean
     *  true => if username available
     *  false => if username alreaddy used.
     */
    public function checkUsername($username){
    	$where = array('username' => $username);
    	$check = $this->getDbTable()->fetchRow($where);
    	
    	if(count($check)!=0){
    		return false; //username already taken.
    	}
    	else{
    		return true; //username available.
    	}
    }
    
    /**
     * 
     * To save new or update existing agent's informtion.
     * @param Reale_Model_Users_Agent
     * @return Reale_Model_Users_Agent | null 
     */
    public function save(Reale_Model_Users_Agent &$agent){
    	
    	$agentdata = array(
    		'agent_id' => $agent->getAgent_id(),
			'agent_name' => $agent->getAgent_name(),
    	    'father_name'=> $agent->getFather_name(),
    	    'mother_name'=> $agent->getMother_name(),
    		'mobile_no' => $agent->getMobile_no(),
    		'alternate_no' => $agent->getAlternate_no(),
    	    'occupation' => $agent->getOccupation(),
    	    'rgrn_date' => $agent->getRgrn_date(),
    	    'dob' => $agent->getDob(),
    	    'applicant_type_id' => $agent->getApplicant_type(),
    	    'gender_id' => $agent->getGender(),
    	    'nationality_id' => $agent->getNationality(),
    	    'marital_status_id' => $agent->getMarital_status(),
    	    'pan' => $agent->getPan(),
    	    'email' => $agent->getEmail(),
    	    'password' => $agent->getPassword()
        );
        if ($agent->getHusband_name()) {
            $agentdata['husband_name'] = $agent->getHusband_name();
        }
        
        
        $padd =  $agent->getPaddress();
        $cadd =  $agent->getCaddress()?$agent->getCaddress():'';
        
        $add_data = array(
        	'agent_id' => $agent->getAgent_id(),
        	'paddress' => $padd->getAddressline(),
        	'pplace' => $padd->getPlace(),
        	'pdistrict' => $padd->getDistrict(),
        	'pstate' => $padd->getState(),
        	'ppostalcode' => $padd->getPostalcode());
        
        if ($cadd) {
            $add_data['caddress'] = $cadd->getAddressline();
            $add_data['cplace'] =  $cadd->getPlace();
        	$add_data['cdistrict'] =  $cadd->getDistrict();
        	$add_data['cstate'] =  $cadd->getState();
        	$add_data['cpostalcode'] =  $cadd->getPostalcode();
        }
        
        $nominee = $agent->getNominee();
        
        $nom_data = array(
        	'agent_id' => $agent->getAgent_id(),
        	'nominee_name' => $nominee->getNominee_name(),
        	'relation' => $nominee->getRelation(),
        	'pan' => $nominee->getPan(),
        	'address' => $nominee->getAddress()->getAddressline(),
        	'place' => $nominee->getAddress()->getPlace(),
        	'district' => $nominee->getAddress()->getDistrict(),
        	'state' => $nominee->getAddress()->getState(),
        	'postalcode' => $nominee->getAddress()->getPostalCode()
        );
        
        $cadd =  $agent->getCaddress()?$agent->getCaddress():'';
        
        $authUser = new Reale_Model_DbTable_AuthUser();
        $authUserdata = array('user_id' => $agent->getAgent_id(),
                              'sec_passwd'=> $agent->getPassword(),
                              'user_type_id'=>'agnt');
            try {
                $this->getDbTable()
                    ->getAdapter()
                    ->beginTransaction();
                    
            $pKey = $this->getDbTable()->insert($agentdata);
            $authUser->insert($authUserdata);
            
            $userRole = new Reale_Model_DbTable_UserRole();
            $userRole->insert(array('user_id' => $agent->getAgent_id(),
            						'role_id' => 'agent'));
            $sponserer = $agent->getSponser();
            $sponserer->sponser($agent);
            $agentAddress = new Reale_Model_DbTable_AgentAddress();
            $agentAddress->insert($add_data);
            
            $agentNominee = new Reale_Model_DbTable_AgentNominee();
            $agentNominee->insert($nom_data);
            
                $this->getDbTable()
                    ->getAdapter()
                    ->commit();
                    
            } catch (Zend_Exception $e) {
                $this->getDbTable()
                    ->getAdapter()
                    ->rollBack();
                throw $e;
            }
            return $agent;
            
        }
    		
}

